import 'dart:async';
import 'dart:collection';

class AsyncQueue {  
  final Queue<Function()> _queue = Queue();  
  int _activeTasks = 0;  
  final int _maxConcurrentTasks;  

  AsyncQueue({int maxConcurrentTasks = 5}) : _maxConcurrentTasks = maxConcurrentTasks;  

  Future<void> add(Future<void> Function() task) async {  
    _queue.add(() async {  
      await task();  
      _activeTasks--;  
      _processQueue();  
    });  

    _processQueue();  
  }  

  void _processQueue() {  
    while (_activeTasks < _maxConcurrentTasks && _queue.isNotEmpty) {  
      final task = _queue.removeFirst();  
      _activeTasks++;  
      task();  
    }  
  }  
} 